package cn.zxf.note.security;

import java.util.Objects;

/**
 * Created by zengxf on 2019/4/9.
 */
public class TokenUtils implements SecurityConstant {

    public static String generate(Integer userId, boolean remember) {
        String token = String.format("ok:%d:%d:%d", userId, System.currentTimeMillis(), remember ? 1 : 0);
        return SecretUtils.encrypt(token);
    }

    public static Integer parse(String token) {
        String str = SecretUtils.decrypt(token);
        if (str.isEmpty())
            return null;

        String[] arr = str.split(":");
        if (arr.length != 4)
            return null;

        String time = arr[2];
        String sign = arr[3];
        long cTime = Long.parseLong(time);
        if (Objects.equals("1", sign)) // remember
            cTime = cTime + VALID_INTERVAL_7D;
        else
            cTime = cTime + VALID_INTERVAL_1H;
        if (cTime < System.currentTimeMillis())
            return null;

        String uid = arr[1];
        return Integer.valueOf(uid);
    }

}
